export const LogCat = typeof plus === 'object' ? {
  main: plus.android.runtimeMainActivity(),
  Environment: plus.android.importClass('android.os.Environment'),
  BufferedWriter: plus.android.importClass('java.io.BufferedWriter'),
  File: plus.android.importClass('java.io.File'),
  FileOutputStream: plus.android.importClass('java.io.FileOutputStream'),
  OutputStreamWriter: plus.android.importClass('java.io.OutputStreamWriter'),
  LogPath: '',  //日志存储目录
  saveDays: 7,   //日志最大存储天数
  list: [],
  init: function () {
    if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) {
      this.LogPath = this.main.getExternalFilesDir(null).getPath();
    } else {
      this.LogPath = this.main.getFilesDir().getPath();
    }
    console.log("LogPath", this.LogPath)
    let fileManager = new this.File(this.LogPath);
    let files = fileManager.listFiles()
    let now = new Date();
    let maxSavedDay = utils.getFormatDate(now - this.saveDays * 24 * 60 * 60 * 1000)
    // 遍历目录下的日志文件,并删除日志最大存储天数前的日志
    for (var i in files) {
      let name = files[i].getName().split('.')[0],
          time = name.split('_')[1]
      if (time <= maxSavedDay && name.search('log_') == 0) {
        files[i].delete()
      }
    }
    console.log('LogPath->', this.LogPath);
  },
  d: function (tag, msg = '') {
    let now = new Date();
    let date = utils.getFormatDate(now);
    let datetime = utils.getFormatDateTime(now);

    msg = (typeof msg !== 'string' ? JSON.stringify(msg) : msg);

    //文件名
    let fileName = this.LogPath + "/log_" + date + ".txt"
    //写入的内容
    let content = `\n${datetime} ${tag}${msg ? ':' + msg : msg}\n`;

    let file = new this.File(this.LogPath);
    if (!file.exists()) {
      file.mkdirs(); //创建父路径
    }
    let fos = null;
    let bw = null;
    try {
      fos = new this.FileOutputStream(fileName, true);
      bw = new this.BufferedWriter(new this.OutputStreamWriter(fos));
      //bw.write(log);
      bw.append(content);
    } catch (e) {
      console.log('e->', e);
    } finally {
      try {
        if (bw != null) {
          bw.close(); //关闭缓冲流
          fos.close(); //关闭文件输出流
        }
      } catch (closeEx) {
        console.log('closeEx->', closeEx);
      }
    }
  },
  readFiles: function () {
    this.list = []
    return new Promise(resolve => {
      const folderPath = this.LogPath;
      this.aFileList = [];
      plus.io.resolveLocalFileSystemURL(folderPath,
          (entry) => {
            var directoryReader = entry.createReader(); //获取读取目录对象
            directoryReader.readEntries(
                (entries) => { //返回的是指定文件夹下的文件列表
                  this.aFileList = entries
                  this.aFileList.forEach(i => {
                    if (/\./.test(i.name)) {
                      this.list.push({name: i.name})
                    }
                  })
                  resolve(this.list)
                  console.log("文件夹下的文件列表", this.list)
                },
                (err) => {
                  resolve(false)
                  console.log("访问目录失败");
                }
            );
          },
          (err) => {
            resolve(false)
            console.log("访问指定目录失败:" + err.message);
          });
    })
  },
  readLogFile(fileName) {
    let filePath = this.LogPath + "/" + fileName
    console.log("readLogFile-fileName", fileName)
    return new Promise(resolve => {
      console.log("readLogFile-fileName111", fileName)
      plus.io.requestFileSystem(plus.io.PRIVATE_DOC,
          function (fs) {
            console.log("readLogFile-filePath", filePath)
            //读取文件
            fs.root.getFile(filePath, {create: true},
                function (fileEntry) {
                  console.log('文件在手机中的路径', fileEntry.fullPath)
                  fileEntry.file(function (file) {
                    var fileReader = new plus.io.FileReader();
                    console.log("getFile:" + JSON.stringify(file));
                    fileReader.readAsText(file, "utf-8")
                    fileReader.onloadend = function (res) { //读取文件内容成功后的回调事件
                      //res.target.result读取到的文件内容信息
                      console.log('最后读取文件内容是=======', res.target.result)
                      resolve(res.target.result)
                    }
                  });
                },
                function (err) {
                  console.error('创建文件失败', err);
                  resolve(false)
                });
          },
          function (e) {
            console.error("Request file system failed: " + e.message);
            resolve(false)
          }
      );
    })
  }
} : {}

export const utils = {
  getFormatDate: (dateString) => {
    const date = new Date(dateString);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month > 9 ? month : '0' + month;
    ;
    day = day > 9 ? day : '0' + day;
    return `${year}-${month}-${day}`;
  },
  getFormatDateTime: (dateString) => {
    const date = new Date(dateString);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let min = date.getMinutes();
    let second = date.getSeconds();

    month = month > 9 ? month : '0' + month;
    ;
    day = day > 9 ? day : '0' + day;
    hour = hour > 9 ? hour : '0' + hour;
    min = min > 9 ? min : '0' + min;
    second = second > 9 ? second : '0' + second;

    return `${year}-${month}-${day} ${hour}:${min}:${second}`;
  }
}
